<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="菜单名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.parent_id" placeholder="一级菜单" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in menuOneOption" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="父级菜单" align="center">
        <template slot-scope="{row}">
          <span>{{ getMenuName(row.parent_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center">
        <template slot-scope="{row}">
          <span>{{ isShowOption[row.is_show] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" align="center" sortable="custom" :class-name="getSortClass('sort')">
        <template slot-scope="{row}">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="路由跳转地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.html_path }}</span>
        </template>
      </el-table-column>
      <el-table-column label="前端页面地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.html_view }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button size="mini" type="success" @click="jumpMenuTwo(row.id)">
            二级菜单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="父级菜单">
          <SearchOptionMenu :menu-id="temp.parent_id" @setSearchMenuId="updateMenuParentId" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-select v-model="temp.is_show" prop="is_show" class="filter-item">
            <el-option v-for="(value,key) in isShowOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="路由地址" prop="路由地址">
          <el-input v-model="temp.html_path" />
        </el-form-item>
        <el-form-item label="页面地址" prop="页面地址">
          <el-input v-model="temp.html_view" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { menuPage, menuCreate, menuUpdate, menuDelete, getMenuOne } from '@/api/rbac'
import waves from '@/directive/waves' // waves directive
import { isInteger } from '@/utils/validate'
import { notifySuccess, formatJson, my_confirm } from '@/utils/tool'
import Pagination from '@/components/Pagination'
import SearchOptionMenu from '@/components/SearchOption/menu'

export default {
  name: 'MenuList',
  components: { Pagination, SearchOptionMenu },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        parent_id: undefined,
        name: undefined
      },
      menuOneOption: [], // 一级菜单的下拉列表
      isShowOption: {
        0: '不显示',
        1: '显示'
      },
      temp: {
        id: undefined,
        parent_id: '',
        name: '',
        is_show: undefined,
        sort: 1,
        html_path: '',
        html_view: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        name: [{ required: true, message: '菜单名称必填', trigger: 'change' }],
        sort: [{ required: true, message: '排序必填且为数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    getMenuOne().then(response => {
      this.menuOneOption = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      menuPage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    // 根据菜单id获取菜单名称
    getMenuName(menuId) {
      if (parseInt(menuId) === 0) {
        return ''
      }
      var menuName = menuId
      this.menuOneOption.forEach(function(item, index) {
        if (item.id === menuId) {
          menuName = item.name
        }
      })
      return menuName
    },
    jumpMenuTwo(id) {
      this.listQuery.parent_id = id
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        parent_id: '',
        name: '',
        is_show: '1',
        sort: '',
        html_path: '',
        html_view: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.parent_id === null || this.temp.parent_id === '') {
            this.temp.parent_id = 0
          }
          menuCreate(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.id = row.id
      this.temp.parent_id = row.parent_id
      this.temp.name = row.name
      this.temp.is_show = row.is_show
      this.temp.html_path = row.html_path
      this.temp.html_view = row.html_view
      this.temp.sort = row.sort
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          menuUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        menuDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['菜单名称', '排序', '跳转地址', '跳转页面']
        const filterVal = ['name', 'sort', 'html_path', 'html_view']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '菜单表'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    updateMenuParentId: function(data) {
      this.temp.parent_id = data.menuId
    }
  }
}
</script>
